package com.example.mobifin_busticket.views.dialogs;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.example.mobifin_busticket.MyApplication;
import com.example.mobifin_busticket.R;
import com.example.mobifin_busticket.controller.databasemanager.DatabaseManager;
import com.example.mobifin_busticket.models.BusModel;
import com.example.mobifin_busticket.views.activities.PinConformActivity;
import com.example.mobifin_busticket.views.activities.SelectSourceCityActivity;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Typeface;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class CancellationPolicyDialog extends Dialog implements
		android.view.View.OnClickListener {
	String busId;
	Date doj;
	DatabaseManager dbmanManager;
	Context mcontext;
	Button btn_ok;
	TextView tvbetween, tvcharges, tvPartialCancellation;
	BusModel CancellationPolicyModel = null;
	LinearLayout ll_policyDetails;
	SimpleDateFormat cancelpolicyformatter = new SimpleDateFormat(
			"yyyy-MM-dd hh:mm a");
	DateFormat cancelpolicydfYmm = new SimpleDateFormat("yyyy-MM-dd");
	String cancelstrHour, cancelstrMin, cancelstrAmpm;
	ArrayList<String> sepratedCancellationList = new ArrayList<String>();
	List<String> arrcancelledpolicyColon = new ArrayList<String>();
	Map<String, String> mcancelpolicyHashMap = null;
	List<Map<String, String>> mainHasmapPlociy = new ArrayList<Map<String, String>>();
	LinearLayout lldynamicaddcancel = null;

	public CancellationPolicyDialog(Context context, String busId)
			throws ParseException {
		super(context);
		// TODO Auto-generated constructor stub
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.cancellationpolicy_dailog);
		btn_ok = (Button) findViewById(R.id.btn_ok);
		tvPartialCancellation = (TextView) findViewById(R.id.tvPartialCancellation);
		ll_policyDetails = (LinearLayout) findViewById(R.id.ll_cancle_fee);
		btn_ok.setOnClickListener(this);
		this.busId = busId;
		this.mcontext = context;
		dbmanManager = new DatabaseManager(mcontext);
		CancellationPolicyModel = dbmanManager.getCancelltionPolicy(busId);
		String strPolicy[] = CancellationPolicyModel.getcancellationPolicy()
				.split(";");
		for (int i = 0; i < strPolicy.length; i++) {
			sepratedCancellationList.add(strPolicy[i]);
			System.out.println("new string at: " + i + ": " + strPolicy[i]);
		}

		try {
			getHourMinfromDept();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String strsepratebySemi = sepratedCancellationList.toString()
				.replace("[", "").replace("]", "");
		Map<Integer, List<String>> map = new HashMap<Integer, List<String>>();
		List<String> seperateArr = null;

		String[] mainStrtoStore = strsepratebySemi.split(",");
		conditionForPolicy(context, mainStrtoStore, seperateArr, map);

	}

	private void conditionForPolicy(Context context, String[] mainStrtoStore,
			List<String> seperateArr, Map<Integer, List<String>> map) {
		// TODO Auto-generated method stub
		List<String> mseperateArr = seperateArr;
		for (int j = 0; j < mainStrtoStore.length; j++) {
			arrcancelledpolicyColon.add(mainStrtoStore[j]);
		}
		for (int k = 0; k < arrcancelledpolicyColon.size(); k++) {
			Log.d("mai", "" + arrcancelledpolicyColon.get(k));

			String[] mai = arrcancelledpolicyColon.get(k).split(":");
			Log.d("maiLentght", "" + mai.length);
			mseperateArr = new ArrayList<String>();
			for (int m = 0; m < mai.length; m++) {
				mseperateArr.add(mai[m]);
			}
			Log.d("seperateArrseperateArrseperateArr", "" + mseperateArr);
			map.put(k, mseperateArr);
		}
		Log.d("colon length", "" + map);
		for (int i = 0; i < map.size(); i++) {
			insidemainloginforlooppcy(i, map);
		}
		Log.d("Finally", mainHasmapPlociy.toString());

		for (int i = 0; i < mainHasmapPlociy.size(); i++) {
			showcancellationPolisy(i);
		}

	}

	private void insidemainloginforlooppcy(int i, Map<Integer, List<String>> map) {
		// TODO Auto-generated method stub
		List<String> temparr = new ArrayList<String>();
		temparr = map.get(i);
		Log.d(" temparr size", "" + temparr.size());

		for (int j = 0; j < temparr.size(); j++) {
			if (seperatePolicydatapcy(i, map, temparr)) {
				break;
			}
		}

	}

	private boolean seperatePolicydatapcy(int i,
			Map<Integer, List<String>> map, List<String> temparr) {
		// TODO Auto-generated method stub
		boolean isBreak = false;
		Log.d("insidede i value ", "" + i);
		if (i == map.size() - 1) {
			Log.d("insidede ", "minue 12313");
			if (("-1").equalsIgnoreCase(temparr.get(1).trim())) {
				Log.d("going in minus one", "minus");
				Calendar cal = Calendar.getInstance(); // creates
				cal.setTime(doj);
				cal.add(Calendar.AM_PM, Integer.parseInt(cancelstrAmpm));
				cal.add(Calendar.HOUR,
						-Integer.parseInt(temparr.get(0).trim().toString()));
				mcancelpolicyHashMap = new HashMap<String, String>();
				if (mcancelpolicyHashMap != null) {
					mcancelpolicyHashMap.clear();
				}
				mcancelpolicyHashMap.put("starttime", "");
				mcancelpolicyHashMap.put("betweentime",
						cancelpolicyformatter.format(cal.getTime()));
				mcancelpolicyHashMap.put("rate",
						temparr.get(temparr.size() - 2));
				mcancelpolicyHashMap.put("absolute",
						temparr.get(temparr.size() - 1));
				mainHasmapPlociy.add(mcancelpolicyHashMap);
				isBreak = true;
			}
		} else if (("0").equals(temparr.get(0).trim())) {
			Log.d("Between 0", "Between");
			Calendar cal = Calendar.getInstance(); // creates
			// calendar
			cal.setTime(doj);
			cal.add(Calendar.AM_PM, Integer.parseInt(cancelstrAmpm));
			cal.add(Calendar.HOUR,
					-Integer.parseInt(temparr.get(1).trim().toString()));
			Calendar calDoj = Calendar.getInstance(); // creates
			// calendar
			calDoj.setTime(doj);
			calDoj.add(Calendar.AM_PM, Integer.parseInt(cancelstrAmpm));
			mcancelpolicyHashMap = new HashMap<String, String>();
			if (mcancelpolicyHashMap != null) {
				mcancelpolicyHashMap.clear();
			}
			mcancelpolicyHashMap.put("starttime",
					cancelpolicyformatter.format(calDoj.getTime()));
			mcancelpolicyHashMap.put("betweentime",
					cancelpolicyformatter.format(cal.getTime()));
			mcancelpolicyHashMap.put("rate", temparr.get(temparr.size() - 2));
			mcancelpolicyHashMap.put("absolute",
					temparr.get(temparr.size() - 1));
			mainHasmapPlociy.add(mcancelpolicyHashMap);
			isBreak = true;
		} else {
			Calendar cal = Calendar.getInstance(); // creates
			Calendar cal2 = Calendar.getInstance(); // creates
			cal.setTime(doj);
			cal.add(Calendar.AM_PM, Integer.parseInt(cancelstrAmpm));
			cal.add(Calendar.HOUR,
					-Integer.parseInt(temparr.get(0).trim().toString()));
			cal2.setTime(doj);
			cal2.add(Calendar.AM_PM, Integer.parseInt(cancelstrAmpm));
			cal2.add(Calendar.HOUR,
					-Integer.parseInt(temparr.get(1).trim().toString()));
			mcancelpolicyHashMap = new HashMap<String, String>();
			if (mcancelpolicyHashMap != null) {
				mcancelpolicyHashMap.clear();
			}
			mcancelpolicyHashMap.put("starttime",
					cancelpolicyformatter.format(cal.getTime()));
			mcancelpolicyHashMap.put("betweentime",
					cancelpolicyformatter.format(cal2.getTime()));
			mcancelpolicyHashMap.put("rate", temparr.get(temparr.size() - 2));
			mcancelpolicyHashMap.put("absolute",
					temparr.get(temparr.size() - 1));
			mainHasmapPlociy.add(mcancelpolicyHashMap);
			isBreak = true;
		}
		return isBreak;

	}

	private void showcancellationPolisy(int i) {
		// TODO Auto-generated method stub
		lldynamicaddcancel = new LinearLayout(mcontext);
		lldynamicaddcancel.setOrientation(LinearLayout.HORIZONTAL);
		LinearLayout.LayoutParams layoutParamsLl = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.MATCH_PARENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);

		layoutParamsLl.setMargins(5, 5, 5, 5);
		lldynamicaddcancel.setLayoutParams(layoutParamsLl);

		TextView txtbetween = new TextView(mcontext);
		TextView txtcharges = new TextView(mcontext);

		LinearLayout.LayoutParams layoutParamsText = new LinearLayout.LayoutParams(
				0, LinearLayout.LayoutParams.WRAP_CONTENT);

		layoutParamsText.weight = 1f;
		layoutParamsText.setMargins(5, 0, 5, 0);

		txtbetween.setLayoutParams(layoutParamsText);
		txtcharges.setGravity(Gravity.RIGHT);
		if (i == mainHasmapPlociy.size() - 1) {
			txtbetween.setText("Before" + " "
					+ mainHasmapPlociy.get(i).get("betweentime"));
		} else {
			txtbetween.setText(Html.fromHtml("Between" + " "
					+ mainHasmapPlociy.get(i).get("betweentime") + " " + "And"
					+ " " + mainHasmapPlociy.get(i).get("starttime")));
		}

		txtcharges.setText(mainHasmapPlociy.get(i).get("rate") + " %");

		txtcharges.setTextColor(Color.BLACK);
		txtbetween.setTextColor(Color.BLACK);
		tvPartialCancellation.setTextColor(Color.BLACK);
		lldynamicaddcancel.addView(txtbetween);
		lldynamicaddcancel.addView(txtcharges);
		ll_policyDetails.addView(lldynamicaddcancel);
		if (CancellationPolicyModel.getpartialCancellationAllowed() == "false") {
			tvPartialCancellation.setText(R.string.partialcancelnotallowed);
			tvPartialCancellation.setTypeface(null, Typeface.BOLD);
		} else {
			tvPartialCancellation.setText(R.string.partialcancelallowed);
			tvPartialCancellation.setTypeface(null, Typeface.BOLD);
		}

	}

	@SuppressWarnings("deprecation")
	private void getHourMinfromDept() throws ParseException {
		Date strDept = cancelpolicyformatter.parse(CancellationPolicyModel
				.getdepartureTime());
		String strDeptime = cancelpolicyformatter.format(strDept);
		Log.e("strDeptime", "" + strDeptime);
		String[] strDeptimearr = strDeptime.split(" ");
		String strDeptimearrHm = strDeptimearr[1];
		String[] strDeptimearrHmSplit = strDeptimearrHm.split(":");
		cancelstrHour = strDeptimearrHmSplit[0];
		cancelstrMin = strDeptimearrHmSplit[1];
		Log.e("hourmin", "" + cancelstrHour + "--?>" + cancelstrMin);
		if (strDeptimearr[2].contains("AM")) {
			cancelstrAmpm = "0";
		} else {
			cancelstrAmpm = "1";
		}
		try {
			doj = cancelpolicydfYmm.parse(CancellationPolicyModel.getdoj());
			doj.setHours(Integer.parseInt(cancelstrHour));
			doj.setMinutes(Integer.parseInt(cancelstrMin));
			Log.e("DateOf join", "" + cancelpolicyformatter.format(doj));
		} catch (ParseException e1) {

		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v.getId() == R.id.btn_ok) {
			dismiss();
		}
	}

}
